<template>
  <div>
    <el-dialog :title="formData.id?'编辑分类':'添加分类'" :visible="showDialog" @close="btnCancel">
      <el-form ref="formData" :model="formData" :rules="rules">
        <el-form-item label="标题" prop="title" required>
          <el-input v-model="formData.title" style="width:90%" />
        </el-form-item>
        <el-form-item label="描述" prop="desc" required>
          <el-input v-model="formData.desc" style="width:90%" />
        </el-form-item>
        <el-form-item label="封面" prop="image">
          <imageUpload ref="imageUpload" />
        </el-form-item>
      </el-form>
      <!-- footer插槽 -->
      <template v-slot:footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button type="primary" size="small" @click="btnOk">确定</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { addCategory, editCategoty } from '@/api/categories'
import imageUpload from '@/components/ImageUpLoad'
export default {
  components: {
    imageUpload
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        title: '',
        desc: '',
        image: ''
      },
      rules: {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        desc: [{ required: true, message: '描述不能为空', trigger: 'blur' }] }
    }
  },
  watch: {
    formData(newObj) {
      console.log(54, newObj)
      // 将图片添加到图片上传组件的数组中
      if (newObj.image) {
        this.$refs.imageUpload.fileList = [{ url: newObj.image }]
      }
    }
  },
  methods: {

    // 确定按钮
    async btnOk() {
      // 校验表单
      await this.$refs.formData.validate()
      this.formData.image = this.$refs.imageUpload.fileList[0].url
      // console.log(53, this.formData)
      if (this.formData.id) {
        // console.log(68, this.formData)
        await editCategoty(this.formData)
      } else {
        //   发请求
        await addCategory(this.formData)
      }

      //   提示用户
      this.$message.success('操作成功')
      //   刷新页面
      //   this.$parent可以获取到父元素的实例,使用非常严格,该子组件不能嵌套在其他组件中
      this.$parent.loadPage()
      //   关闭模态框
      this.$parent.isShowDialog = false
    },
    // 取消
    btnCancel() {
      // 清理数据
      this.formData = {
        title: '',
        desc: '',
        image: ''
      }
      this.$refs.imageUpload.fileList = []
      //   清理校验
      this.$refs.formData.resetFields()
      //   关闭模态kuang
      this.$parent.isShowDialog = false
    }
  }
}
</script>

<style>

</style>
